<template>
  <el-container class="template-layout">
    <!-- 顶部查询 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
          :searchOptions="searchOptions"
          :loading="loading"
          @getSearchData="getSearchData"
          @resetFields="resetFields"
      />
    </el-header>

    <el-main>
      <!-- 工具栏与右侧操作：表格尺寸/显示查询/列设置 -->
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="addItem">{{ $t('common.add') }}</el-button>
          <el-button type="danger" @click="delItems" plain>{{ $t('common.delete') }}</el-button>
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{ $t('table.mini') }}</el-dropdown-item>
                <el-dropdown-item command="small">{{ $t('table.small') }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{ $t('table.medium') }}</el-dropdown-item>
                <el-dropdown-item command="large">{{ $t('table.large') }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :icon="'Search'" circle @click="showSearchHeader = !showSearchHeader" />
          <el-button :icon="'Operation'" circle @click="showColumnSetting = true" />
        </template>
      </zz-PageBar>

      <!-- 表格：列与字段暂留不写，后续补齐 -->
      <zz-Table
          ref="tableRef"
          :key="tableKey"
          :data="tableData"
          :size="tabelSize"
          :loading="loading"
          :page="tablePage"
          :hasPage="true"
          @pageChange="pageChange"
      >
        <vxe-column type="checkbox" fixed="left" width="40" />
        <vxe-column type="seq" fixed="left" width="50" />

        <!-- 动态列渲染：根据 tableColumns -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :width="150"
          >
            <template #default="{ row }">
              <template v-if="column.field === 'userCode'">
                <a @click="editItem(row)">{{ row[column.field] }}</a>
              </template>
              <template v-else>
                {{ row[column.field] }}
              </template>
            </template>
          </vxe-column>
        </template>

        <!-- 操作列 -->
        <vxe-column :title="$t('common.operation')" :width="200" fixed="right">
          <template v-slot="{ row }">
            <zz-TableBtn type="text" :loading="btnLoading" @click="viewItem(row)">{{ $t('common.view') }}</zz-TableBtn>
            <zz-TableBtn type="error" :loading="btnLoading" @click="delItem(row)">{{ $t('common.delete') }}</zz-TableBtn>
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>
  </el-container>

  <!-- 业务组件 -->
  <addUser
      ref="addUserRef"
      v-model="addUserIsOpen"
      @query="query"
  ></addUser>

  <!-- 列设置：使用本地存储，键名 user_columns -->
  <zz-ColumnSetting
      v-model="showColumnSetting"
      :columns="tableColumns"
      :default-columns="defaultTableColumns"
      storage-key="user_columns"
      list-id="user-column-list"
      drawer-class="user-column-setting-drawer"
      @confirm="handleColumnConfirm"
      @cancel="handleColumnCancel"
      @reset="handleColumnReset"
  />
</template>

<script setup>
// import addUser from './components/addUser.vue'
import { computed, getCurrentInstance, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance();

// UI 状态
const showSearchHeader = ref(true);
const showColumnSetting = ref(false);
const loading = ref(false);
const btnLoading = ref(false);


// 初始化
const init = () => {
  // todo:
  loadColumnSettings();
}

// 查询模型与配置
const searchModel = ref({
  userCode: '',
  userName: '',
  sex: '',
  birthDayRange: [],
  telephone: '',
  idNumber: '',
  email: '',
  address: '',
  status: '',
  thirdPartyId: '',
  useSys: '',
  lastLoginIp: '',
  createDateRange: [],
  updateDateRange: [],
});

const searchOptions = computed(() => ({
  model: searchModel,
  column: [
    {
      label: '用户编码',
      type: 'inputText',
      field: 'userCode',
    },
    {
      label: '用户名称',
      type: 'inputText',
      field: 'userName',
    },
    {
      label: '性别',
      type: 'inputText',
      field: 'sex',
    },
    {
      label: '出生日期',
      type: 'datePicker',
      field: 'birthDayRange',
      dateType: 'daterange',
    },
    {
      label: '手机号',
      type: 'inputText',
      field: 'telephone',
    },
    {
      label: '身份证号',
      type: 'inputText',
      field: 'idNumber',
    },
    {
      label: '邮箱',
      type: 'inputText',
      field: 'email',
    },
    {
      label: '地址',
      type: 'inputText',
      field: 'address',
    },
    {
      label: '状态',
      type: 'inputText',
      field: 'status',
    },
    {
      label: '外部id',
      type: 'inputText',
      field: 'thirdPartyId',
    },
    {
      label: '是否使用系统',
      type: 'inputText',
      field: 'useSys',
    },
    {
      label: '最后登录ip',
      type: 'inputText',
      field: 'lastLoginIp',
    },
    {
      label: '创建时间',
      type: 'datePicker',
      field: 'createDateRange',
      dateType: 'daterange',
    },
    {
      label: '更新时间',
      type: 'datePicker',
      field: 'updateDateRange',
      dateType: 'daterange',
    },
  ],
}));

// 查询事件
const getSearchData = (val) => {
  searchModel.value = val;
  query('search');
};
// 重置查询表单
const resetFields = () => {
  searchModel.value = {
    userCode: '',
    userName: '',
    sex: '',
    birthDayRange: [],
    telephone: '',
    idNumber: '',
    email: '',
    address: '',
    status: '',
    thirdPartyId: '',
    useSys: '',
    lastLoginIp: '',
    createDateRange: [],
    updateDateRange: [],
  };
};

// 表格与分页
const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const tabelSize = ref('small');
const tableRef = ref(null);

// 处理表格大小变化
const handleSizeChange = (size) => { tabelSize.value = size; };

// 列配置与本地存储键
const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
const tableKey = ref(0);

// 当前列配置与默认列
const tableColumns = ref([
    {
      field: "userCode",
      title: "用户编码",
      visible: true,
      fixed: 'left',
    },
    {
      field: "userName",
      title: "用户名称",
      visible: true,
      fixed: null,
    },
    {
      field: "avatarFileName",
      title: "头像url",
      visible: true,
      fixed: null,
    },
    {
      field: "sex",
      title: "性别",
      visible: true,
      fixed: null,
    },
    {
      field: "birthDay",
      title: "出生日期",
      visible: true,
      fixed: null,
    },
    {
      field: "age",
      title: "年龄",
      visible: true,
      fixed: null,
    },
    {
      field: "school",
      title: "毕业院校",
      visible: true,
      fixed: null,
    },
    {
      field: "education",
      title: "学历",
      visible: true,
      fixed: null,
    },
    {
      field: "major",
      title: "专业",
      visible: true,
      fixed: null,
    },
    {
      field: "jobTitle",
      title: "职称",
      visible: true,
      fixed: null,
    },
    {
      field: "jobPost",
      title: "职务",
      visible: true,
      fixed: null,
    },
    {
      field: "companyId",
      title: "公司id",
      visible: true,
      fixed: null,
    },
    {
      field: "companyCode",
      title: "公司编码",
      visible: true,
      fixed: null,
    },
    {
      field: "companyName",
      title: "公司名称",
      visible: true,
      fixed: null,
    },
    {
      field: "departmentId",
      title: "部门id",
      visible: true,
      fixed: null,
    },
    {
      field: "departmentCode",
      title: "部门编码",
      visible: true,
      fixed: null,
    },
    {
      field: "departmentName",
      title: "部门名称",
      visible: true,
      fixed: null,
    },
    {
      field: "loginAccount",
      title: "登录账号",
      visible: true,
      fixed: null,
    },
    {
      field: "passWord",
      title: "登录密码",
      visible: true,
      fixed: null,
    },
    {
      field: "role",
      title: "角色名称",
      visible: true,
      fixed: null,
    },
    {
      field: "telephone",
      title: "手机号",
      visible: true,
      fixed: null,
    },
    {
      field: "idNumber",
      title: "身份证号",
      visible: true,
      fixed: null,
    },
    {
      field: "email",
      title: "邮箱",
      visible: true,
      fixed: null,
    },
    {
      field: "address",
      title: "地址",
      visible: true,
      fixed: null,
    },
    {
      field: "status",
      title: "状态",
      visible: true,
      fixed: null,
    },
    {
      field: "thirdPartyId",
      title: "外部id",
      visible: true,
      fixed: null,
    },
    {
      field: "useSys",
      title: "是否使用系统",
      visible: true,
      fixed: null,
    },
    {
      field: "lastLoginIp",
      title: "最后登录ip",
      visible: true,
      fixed: null,
    },
    {
      field: "lastLoginTime",
      title: "最后登录时间",
      visible: true,
      fixed: null,
    },
    {
      field: "failureTime",
      title: "失效时间",
      visible: true,
      fixed: null,
    },
    {
      field: "createDate",
      title: "创建时间",
      visible: true,
      fixed: null,
    },
    {
      field: "updateDate",
      title: "更新时间",
      visible: true,
      fixed: null,
    },
]);
const defaultTableColumns = ref([
      {
        field: "userCode",
        title: "用户编码",
        visible: true,
        fixed: 'left',
      },
      {
        field: "userName",
        title: "用户名称",
        visible: true,
        fixed: null,
      },
      {
        field: "avatarFileName",
        title: "头像url",
        visible: true,
        fixed: null,
      },
      {
        field: "sex",
        title: "性别",
        visible: true,
        fixed: null,
      },
      {
        field: "birthDay",
        title: "出生日期",
        visible: true,
        fixed: null,
      },
      {
        field: "age",
        title: "年龄",
        visible: true,
        fixed: null,
      },
      {
        field: "school",
        title: "毕业院校",
        visible: true,
        fixed: null,
      },
      {
        field: "education",
        title: "学历",
        visible: true,
        fixed: null,
      },
      {
        field: "major",
        title: "专业",
        visible: true,
        fixed: null,
      },
      {
        field: "jobTitle",
        title: "职称",
        visible: true,
        fixed: null,
      },
      {
        field: "jobPost",
        title: "职务",
        visible: true,
        fixed: null,
      },
      {
        field: "companyId",
        title: "公司id",
        visible: true,
        fixed: null,
      },
      {
        field: "companyCode",
        title: "公司编码",
        visible: true,
        fixed: null,
      },
      {
        field: "companyName",
        title: "公司名称",
        visible: true,
        fixed: null,
      },
      {
        field: "departmentId",
        title: "部门id",
        visible: true,
        fixed: null,
      },
      {
        field: "departmentCode",
        title: "部门编码",
        visible: true,
        fixed: null,
      },
      {
        field: "departmentName",
        title: "部门名称",
        visible: true,
        fixed: null,
      },
      {
        field: "loginAccount",
        title: "登录账号",
        visible: true,
        fixed: null,
      },
      {
        field: "passWord",
        title: "登录密码",
        visible: true,
        fixed: null,
      },
      {
        field: "role",
        title: "角色名称",
        visible: true,
        fixed: null,
      },
      {
        field: "telephone",
        title: "手机号",
        visible: true,
        fixed: null,
      },
      {
        field: "idNumber",
        title: "身份证号",
        visible: true,
        fixed: null,
      },
      {
        field: "email",
        title: "邮箱",
        visible: true,
        fixed: null,
      },
      {
        field: "address",
        title: "地址",
        visible: true,
        fixed: null,
      },
      {
        field: "status",
        title: "状态",
        visible: true,
        fixed: null,
      },
      {
        field: "thirdPartyId",
        title: "外部id",
        visible: true,
        fixed: null,
      },
      {
        field: "useSys",
        title: "是否使用系统",
        visible: true,
        fixed: null,
      },
      {
        field: "lastLoginIp",
        title: "最后登录ip",
        visible: true,
        fixed: null,
      },
      {
        field: "lastLoginTime",
        title: "最后登录时间",
        visible: true,
        fixed: null,
      },
      {
        field: "failureTime",
        title: "失效时间",
        visible: true,
        fixed: null,
      },
      {
        field: "createDate",
        title: "创建时间",
        visible: true,
        fixed: null,
      },
      {
        field: "updateDate",
        title: "更新时间",
        visible: true,
        fixed: null,
      },
]);

// 处理列设置确认
const handleColumnConfirm = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['user_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};
// 处理列设置取消
const handleColumnCancel = () => { loadColumnSettings(); };
// 处理列设置重置
const handleColumnReset = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['user_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};

// 加载已保存列设置
const loadColumnSettings = () => {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY))?.['user_columns'];
    if (saved) tableColumns.value = saved;
    tableKey.value += 1;
  } catch (e) {
    console.error('加载列设置失败:', e);
  }
};

// 查询
const query = async (mode) => {
  loading.value = true;
  if (mode === 'search') {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    }
  }
  // TODO: 接入测试管理查询接口，替换为真实 API
  let params = dealParams();
  let res = await proxy.$API.userManagement.user.queryWithPage.post(params);
  if (res.code === '01') {
    tableData.value = res.bizList;
    tablePage.value.total = res.total;
    tablePage.value.pageSize = res.pageSize;
  }
  loading.value = false;
};
// 处理查询参数
const dealParams = () => {
  let params = {
    ...searchModel.value,
  };

  // 其他的参数转化逻辑，如日期格式等
    params.birthDayRange = params.birthDayRange.map((date, index) => {
      if (index == 0) {
        return proxy.$TOOL.format.formatDateTime(date)
      } else {
        return proxy.$TOOL.format.getEndOfDay(date)
      }
    })
    params.createDateRange = params.createDateRange.map((date, index) => {
      if (index == 0) {
        return proxy.$TOOL.format.formatDateTime(date)
      } else {
        return proxy.$TOOL.format.getEndOfDay(date)
      }
    })
    params.updateDateRange = params.updateDateRange.map((date, index) => {
      if (index == 0) {
        return proxy.$TOOL.format.formatDateTime(date)
      } else {
        return proxy.$TOOL.format.getEndOfDay(date)
      }
    })
  return params
}

// 业务操作占位
const addUserRef = ref(null)
const addUserIsOpen = ref(false)
const addItem = () => {
  addUserIsOpen.value = true
  addUserRef.value.title = '新增用户'
};
const delItems = async () => {
  const rows = tableRef.value?.getCheckboxRecords?.() || [];
  if (rows.length === 0) return proxy.$message.warning('请选择要删除的数据');
  let ids = rows.map((e) => e.userId)
  proxy
    .$confirm(`确定要删除吗`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.userManagement.user.deleteBatch.post(ids);
      if (res.code === "01") {
        query("search");
        proxy.$message.success("删除成功");
      } else {
        proxy.$message.error(res.msg || "删除失败");
      }
    })
    .catch(() => {
      proxy.$message.info("已取消删除");
    });
};
const delItem = async (row) => {
  let id = row.userId;
  proxy
    .$confirm(`确定要删除吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.userManagement.user.delete.get(id);
      if (res.code === "01") {
        query("search");
        proxy.$message.success("删除成功");
      } else {
        proxy.$message.error(res.msg || "删除失败");
      }
    })
    .catch(() => {
      proxy.$message.info("已取消删除");
    });
};
const viewItem = (row) => {
  addUserIsOpen.value = true
  addUserRef.value.type = 'view'
  addUserRef.value.model = {...row}
};
const editItem = (row) => {
  addUserIsOpen.value = true
  addUserRef.value.type = 'edit'
  addUserRef.value.model = {...row}
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage
  searchModel.value.queryParam.pageSize = page.pageSize
  query()
}

onMounted(() => {
  init();
  query('search');
});
</script>

<style lang="less" scoped></style>